package com.aaa.wash.service.impl;

import com.aaa.common.entity.*;
import com.aaa.common.util.CustomException;
import com.aaa.common.util.Result;
import com.aaa.common.util.ResultStatus;
import com.aaa.common.util.TokenUtil;
import com.aaa.common.vo.Page;
import com.aaa.common.vo.WashNumberStatisticVO;
import com.aaa.wash.dao.CarWashRecordDao;
import com.aaa.wash.dao.FrontUserStoreDao;
import com.aaa.wash.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * (CarWashRecord)表服务实现类
 *
 * @author makejava
 * @since 2025-09-24 15:48:55
 */
@Service("carWashRecordService")
public class CarWashRecordServiceImpl implements CarWashRecordService {
    @Resource
    private CarWashRecordDao carWashRecordDao;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RemoteStationService remoteStationService;
    @Resource
    private FrontUserStoreDao frontUserStoreDao;
    @Resource
    private WashCarCouponService washCarCouponService;
    @Resource
    private RemoteUserBalanceService remoteUserBalanceService;
    @Resource
    private RemoteUserBalanceLogService remoteUserBalanceLogService;
    @Resource
    private RemoteUserIntegralService remoteUserIntegralService;
    @Resource
    private RemoteUserIntegralLogService remoteUserIntegralLogService;


    @Override
    public List<CarWashRecord> selectAll(Integer storeId) {
        String userId = TokenUtil.getUserId(request);
        return carWashRecordDao.selectAll(storeId, Integer.valueOf(userId));
    }

    @Override
    public CarWashRecord selectOne(Integer orderId) {
        String userId = TokenUtil.getUserId(request);
        return carWashRecordDao.selectOne(orderId, Integer.valueOf(userId));
    }

    @Override
    public CarWashRecord getLatestRecord(String carNo, Long storeId) {
        return carWashRecordDao.findLatestRecordByCarNoAndStoreId(carNo, storeId);
    }

    @Override
    public CarWashRecord selectWashingCar() {
        String userId = TokenUtil.getUserId(request);
        return carWashRecordDao.selectWashingCar(Integer.valueOf(userId));
    }

    @Override
    public List<CarWashRecord> selectWashNumberByUserIdAndTime(Integer userId, String monthFormat) {
        return carWashRecordDao.selectWashNumberByUserIdAndTime(userId, monthFormat);
    }

    @Override
    public Integer selectNumber() {
        String userId = TokenUtil.getUserId(request);
        return carWashRecordDao.selectNumber(Integer.valueOf(userId));
    }

    /**
     * 通过店铺id查询该店铺的洗车次数
     *
     * @param storeId 店铺id
     * @return 查询结果
     */
    @Override
    public List<WashNumberStatisticVO> selectWashNumberByStoreId(Integer storeId) {
        return carWashRecordDao.selectWashNumberByStoreId(storeId);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param orderId 主键
     * @return 实例对象
     */
    @Override
    public CarWashRecord queryById(Integer orderId) {
        return this.carWashRecordDao.queryById(orderId);
    }

    /**
     * 分页查询
     *
     * @param page 筛选条件
     * @return 查询结果
     */
    @Override
    public PageInfo queryByPage(Page<CarWashRecord> page) {
        //分页操作  分页参数一定要进行传递
        if (page == null || page.getPageNo() == null || page.getPageNo() == 0 || page.getPageSize() == null || page.getPageSize() == 0) {
            //进行业务编写时，可以抛出自定义异常
            throw new CustomException(ResultStatus.PARAM_NOT_EMPTY.getReturnCode(),
                    ResultStatus.PARAM_NOT_EMPTY.getReturnMessage());
        }
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        //获取查询对象
        CarWashRecord carWashRecord = page.getData();
        return new PageInfo(carWashRecordDao.queryAllByLimit(carWashRecord));
    }

    /**
     * 新增数据
     *
     * @param carWashRecord 实例对象
     * @return 实例对象
     */
    @Override
    public CarWashRecord insert(CarWashRecord carWashRecord) {
        String userId = TokenUtil.getUserId(request);
        carWashRecord.setUserId(Integer.valueOf(userId));
        carWashRecord.setWashStatus("0");
        if (carWashRecord.getProductId() != null) {
            carWashRecord.setIsUsed("1");
        } else {
            carWashRecord.setIsUsed("0");
        }
        this.carWashRecordDao.insert(carWashRecord);

        Station station = new Station();
        station.setStation(carWashRecord.getStationId());
        station.setIdle("1");
        remoteStationService.edit(station);

        FrontUserStore frontUserStore = new FrontUserStore();
        frontUserStore.setStoreId(carWashRecord.getStoreId());
        FrontUserStore frontUserStore1 = frontUserStoreDao.selectByStoreIdAndUserId(frontUserStore.getStoreId(), Integer.valueOf(userId));
        if (frontUserStore1 == null) {
            frontUserStoreDao.insert(frontUserStore.getStoreId(), Integer.valueOf(userId));
        }
        return carWashRecord;
    }

    /**
     * 修改数据
     *
     * @param carWashRecord 实例对象
     * @return 实例对象
     */
    @Override
    public CarWashRecord update(CarWashRecord carWashRecord) {
        Station station = new Station();
        if (carWashRecord.getProductId() == null) {
            station.setStation(carWashRecord.getStation());
        } else {
            station.setStation(carWashRecord.getStationId());
        }
        station.setIdle("0");
        remoteStationService.edit(station);
//        获取洗车时间
        Integer useTime = carWashRecord.getUseTime();
//        获取用户余额
        Result result = remoteUserBalanceService.selectMoneyByUserIdAndStoreId(carWashRecord.getUserId(),carWashRecord.getStoreId());
        Map data = (Map) result.getData();
        Double amount = (Double) data.get("amount");
//        获取用户积分
        Result result1 = remoteUserIntegralService.selectJiFenUseStoreId(carWashRecord.getUserId(),carWashRecord.getStoreId());
        List data1 = (List) result1.getData();
        Integer credits = 0;
        if (data1.size() != 0){
            Map userIntegral1 = (Map) data1.get(0);
             credits = (Integer) userIntegral1.get("credits");
        }else {
             credits = 0;
        }
//        获取优惠券
        WashCarCoupon washCarCoupon = washCarCouponService.queryById(carWashRecord.getProductId());
//        新用户
        if (carWashRecord.getIsNew().equals("0")) {
            if (useTime <= 3) {
//                前十分钟1块
                carWashRecord.setTotalAmount(1.0);
            } else {
//                超出0.5一分钟
                carWashRecord.setTotalAmount(1.0 + ((useTime - 3) * 0.5));
            }
//            使用优惠券
            JieSuan(carWashRecord, amount, credits, washCarCoupon);
//            老用户
        } else if (carWashRecord.getIsNew().equals("1")) {
            if (useTime <= 3) {
//                前十分钟8块
                carWashRecord.setTotalAmount(8.0);
            } else {
//                超出0.5一分钟
                carWashRecord.setTotalAmount(8.0 + ((useTime - 3) * 0.5));
            }
//            使用优惠券
            JieSuan(carWashRecord, amount, credits, washCarCoupon);
        }
        this.carWashRecordDao.update(carWashRecord);
        return this.queryById(carWashRecord.getOrderId());
    }

    private void JieSuan(CarWashRecord carWashRecord, Double amount, Integer credits, WashCarCoupon washCarCoupon) {
        if (carWashRecord.getProductId() != null) {
            Integer couponMoney = washCarCoupon.getCouponMoney();
//                使用优惠券之后实付金额大于等于0
            if (carWashRecord.getTotalAmount() - couponMoney >= 0) {
                carWashRecord.setPayMoney(carWashRecord.getTotalAmount() - couponMoney);
//                    余额大于等于实付金额
                if (amount >= carWashRecord.getPayMoney()) {
                    WashCarCoupon washCarCoupon1 = new WashCarCoupon();
                    washCarCoupon1.setId(washCarCoupon.getId());
                    washCarCoupon1.setIsUsed("1");
                    washCarCouponService.update(washCarCoupon1);
//                        扣钱日志
                    UserBalanceLog userBalanceLog = new UserBalanceLog();
                    userBalanceLog.setUserId(carWashRecord.getUserId());
                    userBalanceLog.setStoreId(carWashRecord.getStoreId());
                    userBalanceLog.setExpenditure(carWashRecord.getPayMoney());
                    remoteUserBalanceLogService.add(userBalanceLog);
//                        更新余额
                    UserBalance userBalance1 = new UserBalance();
                    userBalance1.setUserId(carWashRecord.getUserId());
                    userBalance1.setAmount(amount - carWashRecord.getPayMoney());
                    userBalance1.setStoreId(carWashRecord.getStoreId());
                    remoteUserBalanceService.add(userBalance1);
//                        设置积分
                    UserIntegral userIntegral = new UserIntegral();
                    userIntegral.setUserId(carWashRecord.getUserId());
                    userIntegral.setCredits(credits + carWashRecord.getPayMoney().intValue());
                    userIntegral.setStoreId(carWashRecord.getStoreId());
                    remoteUserIntegralService.add(userIntegral);
//                        积分日志
                    UserIntegralLog userIntegralLog = new UserIntegralLog();
                    userIntegralLog.setUserId(carWashRecord.getUserId());
                    userIntegralLog.setStoreId(carWashRecord.getStoreId());
                    userIntegralLog.setExpendScore(null);
                    userIntegralLog.setArrivalScore(carWashRecord.getPayMoney().intValue());
                    remoteUserIntegralLogService.add(userIntegralLog);
                } else {
//                        余额不足
                    throw new CustomException(ResultStatus.USER_BALANCE_NOT_ENOUGH.getReturnCode(),
                            ResultStatus.USER_BALANCE_NOT_ENOUGH.getReturnMessage());
                }
            } else {
//                使用优惠券之后实付金额小于0，实际金额设置为0
                carWashRecord.setPayMoney(0.0);
                WashCarCoupon washCarCoupon1 = new WashCarCoupon();
                washCarCoupon1.setId(washCarCoupon.getId());
                washCarCoupon1.setIsUsed("1");
                washCarCouponService.update(washCarCoupon1);
            }
        } else {
//                不用优惠券
            carWashRecord.setPayMoney(carWashRecord.getTotalAmount());
            if (amount >= carWashRecord.getPayMoney()) {
//                        扣钱日志
                UserBalanceLog userBalanceLog = new UserBalanceLog();
                userBalanceLog.setUserId(carWashRecord.getUserId());
                userBalanceLog.setStoreId(carWashRecord.getStoreId());
                userBalanceLog.setExpenditure(carWashRecord.getPayMoney());
                remoteUserBalanceLogService.add(userBalanceLog);
//                        更新余额
                UserBalance userBalance1 = new UserBalance();
                userBalance1.setUserId(carWashRecord.getUserId());
                userBalance1.setAmount(amount - carWashRecord.getPayMoney());
                userBalance1.setStoreId(carWashRecord.getStoreId());
                remoteUserBalanceService.add(userBalance1);
//                        设置积分
                UserIntegral userIntegral = new UserIntegral();
                userIntegral.setUserId(carWashRecord.getUserId());
                userIntegral.setCredits(credits + carWashRecord.getPayMoney().intValue());
                userIntegral.setStoreId(carWashRecord.getStoreId());
                remoteUserIntegralService.add(userIntegral);
//                        积分日志
                UserIntegralLog userIntegralLog = new UserIntegralLog();
                userIntegralLog.setUserId(carWashRecord.getUserId());
                userIntegralLog.setStoreId(carWashRecord.getStoreId());
                userIntegralLog.setExpendScore(null);
                userIntegralLog.setArrivalScore(carWashRecord.getPayMoney().intValue());
                remoteUserIntegralLogService.add(userIntegralLog);
            }else {
//                        余额不足
                throw new CustomException(ResultStatus.USER_BALANCE_NOT_ENOUGH.getReturnCode(),
                        ResultStatus.USER_BALANCE_NOT_ENOUGH.getReturnMessage());
            }

        }
    }

    /**
     * 通过主键删除数据
     *
     * @param orderId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer orderId) {
        return this.carWashRecordDao.deleteById(orderId) > 0;
    }
}
